package com.manli.api.service;

import com.manli.api.base.exception.MyException;
import com.manli.api.dto.GoodsDef;
import com.manli.api.pojo.QueryParamsGoodsModel;
import com.manli.api.pojo.QueryParamsGoodsModelDel;
import com.manli.api.util.ObjectEmptyUtil;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.List;
import com.manli.api.pojo.Result;
import com.manli.api.util.ResultUtil;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import com.manli.api.pojo.QueryParams;
import com.manli.api.dao.GoodsModelDao;
import com.manli.api.dto.GoodsModel;
import org.springframework.transaction.annotation.Transactional;


@Service("goodsModelService")
public class GoodsModelService {
    @Autowired
    GoodsModelDao goodsModelDao;
    @Autowired
    SQLManager sqlManager;

    
    public Result queryPage(QueryParams params) {
        /**
        * sql中表名需要修改
        */
        StringBuffer sql = new StringBuffer("select * from goods_model where 1=1 ");

        SQLReady sqlReady = new SQLReady(sql.toString());

        PageQuery<GoodsModel> pageQuery = new PageQuery<GoodsModel>(params.getPage(),params.getLimit());
        PageQuery<GoodsModel> query =sqlManager.execute(sqlReady,GoodsModel.class,pageQuery);
        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    public Result queryPage1(QueryParamsGoodsModel params) {
        /**
         * sql中表名需要修改
         */
        StringBuffer sql = new StringBuffer("SELECT " +
                " a.*, " +
                " b.goods_name, " +
                " c.branch_name, " +
                " d.partner_name,  " +
                "if(a.status = 1,'启用','禁用') status_name " +
                "FROM " +
                " goods_model a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " LEFT JOIN branch c ON b.branch_id = c.branch_id " +
                " LEFT JOIN partner d ON b.partner_id = d.partner_id status != -1 ");

        sql.append(StringUtils.isEmpty(params.getGoodsName())?"":" and b.goods_name like '%" + params.getGoodsName() + "%'");
        sql.append(params.getBranchId() == null?"":" and b.branch_id = " + params.getBranchId());
        sql.append(params.getPartnerId() == null?"":" and b.partner_id = " + params.getPartnerId());
        sql.append(params.getStatus() == null?"":" and a.status = " + params.getStatus());
        sql.append(params.getGoodsDefId() == null?"":" and a.goods_def_id = " + params.getGoodsDefId());
        SQLReady sqlReady = new SQLReady(sql.toString());

        PageQuery<GoodsModel> pageQuery = new PageQuery<GoodsModel>(params.getPage(),params.getLimit());
        PageQuery<GoodsModel> query =sqlManager.execute(sqlReady,GoodsModel.class,pageQuery);
        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    
    public Result queryAll(QueryParamsGoodsModel params) {
        if(params.getGoodsDefId() == null){
            return ResultUtil.error(-1,"商品defid参数缺失");
        }
        String sql = "select * from goods_model where status != -1 and goods_def_id = " + params.getGoodsDefId();
        List<GoodsModel> list = goodsModelDao.execute(sql);
        return ResultUtil.success(list);
    }

    
    public Result getById(Integer goodsModelId) {
        GoodsModel goodsModel = goodsModelDao.single(goodsModelId);
        return ResultUtil.success(goodsModel);
    }

    @Transactional
    public Result save(GoodsModel goodsModel) {
        //判断值为空
        ObjectEmptyUtil.goodsModelIsEmpty(goodsModel);

        List<GoodsModel> list = goodsModelDao.execute("select * from goods_model where goods_model_name = ? and goods_def_id = ?",goodsModel.getGoodsModelName(),goodsModel.getGoodsDefId());
        if(list.size() > 0){
            return ResultUtil.error(-1,"商品规格名称不能重复");
        }

        goodsModelDao.insert(goodsModel);
        return ResultUtil.success();
    }

    @Transactional
    public Result updateById(GoodsModel goodsModel) {
        //如果是活动商品只能新增商品不能改规格
        SQLReady sqlReady = new SQLReady("select * from goods_model where goods_model_id = ?", goodsModel.getGoodsModelId());
        List<GoodsModel> defList = sqlManager.execute( sqlReady,GoodsModel.class);
        if(defList.size() > 0){
            if(goodsModel.getGoodsModelName() != null){
                if(!goodsModel.getGoodsModelName().equals(defList.get(0).getGoodsModelName())){
                    return ResultUtil.error(-1,"不能修改规格名称");
                }
            }
            if(goodsModel.getGoodsModelSalePrice() != null){
                if(goodsModel.getGoodsModelSalePrice().doubleValue() != defList.get(0).getGoodsModelSalePrice().doubleValue()){
                    return ResultUtil.error(-1,"活动商品不能修改价格");
                }
            }
        }

        goodsModelDao.updateTemplateById(goodsModel);
        return ResultUtil.success();
    }
    @Transactional
	public Result updateTemplateById(GoodsModel goodsModel) {
        goodsModelDao.updateTemplateById(goodsModel);
        return ResultUtil.success();
    }
    @Transactional
    public Result removeById(QueryParamsGoodsModelDel goodsModelId) {
        if(goodsModelId.getGoodsModelId() == null){
            return ResultUtil.error(-1,"规格id为空");
        }
        goodsModelDao.executeUpdate("update goods_model set status = -1 where goods_model_id = ?",goodsModelId.getGoodsModelId());
        return ResultUtil.success();
    }

    @Transactional
    public Result removeByIds(List<Integer> ids) {
        for (Integer id:ids) {
            goodsModelDao.executeUpdate("update goods_model set status = -1 where goods_model_id = ?",id);
        }
        return ResultUtil.success();
    }

    @Transactional
    public Result listSave(List<GoodsModel> goodsModels) {
        goodsModels.forEach(goodsModel -> {
            //判断值为空
            ObjectEmptyUtil.goodsModelIsEmpty(goodsModel);

            //如果是活动商品，只能添加一种商品规格
            String sql = "select * from goods_def where goods_def_id = ?";
            SQLReady sqlReady = new SQLReady(sql,goodsModel.getGoodsDefId());
            List<GoodsDef> defList = sqlManager.execute(sqlReady, GoodsDef.class);
            if(defList.size()> 0){
                if(defList.get(0).getApplyActivityTypeId() != null){
                    List<GoodsModel> list1 = goodsModelDao.execute("select * from goods_model where goods_def_id = ?",goodsModel.getGoodsDefId());
                    if(list1.size() > 0){
                        throw new MyException(-1,"活动商品规格只能有一种");
                    }
                }
            }

            List<GoodsModel> list = goodsModelDao.execute("select * from goods_model where goods_model_name = ? and goods_def_id = ?",goodsModel.getGoodsModelName(),goodsModel.getGoodsDefId());
            if(list.size() > 0){
                throw new MyException(-1,"规格名" + goodsModel.getGoodsModelName() + "重复");
            }
            goodsModelDao.insert(goodsModel);
        });
        return ResultUtil.success();
    }
}
